﻿using Basic.FormDAL;
using Basic.FormModel.DB;
using Basic.FormModel.QueryGroup;
using Basic.FormRemoteModel.QueryGroup.Model;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;

namespace Basic.FormCollect.lmpl
{
    internal class QueryGroupCollect : IQueryGroupCollect
    {
        private readonly IPhysicalQueryGroupDAL _BasicDAL;

        public QueryGroupCollect ( IPhysicalQueryGroupDAL basicDAL )
        {
            this._BasicDAL = basicDAL;
        }

        public void Clear ( long formId )
        {
            long[] ids = this._BasicDAL.Gets(a => a.FormId == formId, a => a.Id);
            if ( !ids.IsNull() )
            {
                this._BasicDAL.Delete(ids);
            }
        }
        public long Add ( QueryGroupAdd data )
        {
            if ( this._BasicDAL.IsExists(c => c.TableId == data.TableId && c.ParentId == data.ParentId && c.GroupName == data.GroupName) )
            {
                throw new ErrorException("form.query.table.group.name.repeat");
            }
            DBPhysicalQueryGroup add = data.ConvertMap<QueryGroupAdd, DBPhysicalQueryGroup>();
            add.Sort = this._BasicDAL.GetMaxSort(data.TableId, data.ParentId) + 1;
            return this._BasicDAL.Add(add);
        }
        public DBPhysicalQueryGroup Get ( long id )
        {
            return this._BasicDAL.Get(id);
        }
        public bool Set ( DBPhysicalQueryGroup group, QueryGroupSet set )
        {
            if ( ( set.ParentId != group.ParentId || set.GroupName != set.GroupName ) && this._BasicDAL.IsExists(c => c.TableId == group.TableId
            && c.ParentId == set.ParentId
            && c.GroupName == set.GroupName) )
            {
                throw new ErrorException("form.query.table.group.name.repeat");
            }
            QueryGroupSetDto data = set.ConvertMap<QueryGroupSet, QueryGroupSetDto>();
            if ( group.ParentId != set.ParentId )
            {
                data.Sort = this._BasicDAL.GetMaxSort(group.TableId, data.ParentId) + 1;
            }
            else
            {
                data.Sort = group.Sort;
            }
            return this._BasicDAL.Update(group, data);
        }

        public Result[] GetsByFormId<Result> ( long formId ) where Result : class, new()
        {
            return this._BasicDAL.Gets<Result>(a => a.FormId == formId, "Sort");
        }

        public Result[] GetsByTableId<Result> ( long tableId ) where Result : class, new()
        {
            return this._BasicDAL.Gets<Result>(a => a.TableId == tableId, "Sort");
        }

        public void Delete ( DBPhysicalQueryGroup source )
        {
            this._BasicDAL.Delete(source.Id);
        }

        public void ClearByTableId ( long tableId )
        {
            long[] ids = this._BasicDAL.Gets(a => a.TableId == tableId, a => a.Id);
            if ( !ids.IsNull() )
            {
                this._BasicDAL.Delete(ids);
            }
        }
    }
}
